package org.xiaov.extra.mail.strategy.impl;

import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xiaov.bean.mail.Mail;
import org.xiaov.core.string.StringHelper;
import org.xiaov.extra.mail.strategy.MailStrategy;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Locale;

/**
 * <p>
 * 模板文件邮件
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/2/26 12:36
 */
@Service
public class TemplateMail implements MailStrategy {
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private TemplateEngine templateEngine;

    @Override
    public void sendMail(Mail mail) {
        try {
            //使用thymeleaf模板引擎
            final Context ctx = new Context(new Locale(""));
            ctx.setVariables(mail.getParams());
            final String content = templateEngine.process(mail.getTemplatePath(), ctx);
            //消息
            final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
            message.setFrom(mail.getFrom());
            message.setTo(mail.getTo());
            message.setSubject(mail.getTitle());
            message.setText(content, true);
            javaMailSender.send(mimeMessage);
            log.info("模板邮件已经发送{}。", StringHelper.printArray(mail.getTo()));
        } catch (Exception e) {
            log.error("发送模板邮件【{}】时发生异常！", mail.getTemplatePath(),e);
            throw new MailSendException("发送模板邮件【" + mail.getTemplatePath() + "】时发生异常！", e);
        }
    }
}
